package momo.app.status;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import momo.app.structure.Peer;
import momo.app.util.ConnectionTest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class SendStatusMsgThread extends Thread
{
	private Log log = LogFactory.getLog(SendStatusMsgThread.class);
	private final int timeout = 30 * 1000;
	private Peer peer;
	private String dataToSend; 
	
	public SendStatusMsgThread(Peer peer, String dataToSend)
	{
		this.peer = peer;
		this.dataToSend = dataToSend;
		this.start();
	}
	
	public void run()
	{
		try
		{
			InetAddress address = peer.getAddressToUse();
			if ( address == null )
			{
				ConnectionTest testConnection = new ConnectionTest(peer);
				address = testConnection.testConnection();
				peer.setAddressToUse(address);
			}
			
			if ( peer.getAddressToUse() == null )
				throw new IOException();
			
			Socket sock = new Socket();
			sock.connect(new InetSocketAddress(peer.getAddressToUse(), peer.getStatusPort()), timeout);
			PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
			out.println(dataToSend);
			out.flush();
			out.close();
			sock.close();
		}catch(IOException ioe)
		{
//			if error reach here, it usually means cannot connect
//			if thats the case why i never remove this peer from graph?
//			cos for now i m considering him as in a private network where i cannot reach him
//			but i can reach him thro other peers by broadcasting
			
			if ( log.isErrorEnabled() ) {
				log.error("IOException", ioe);
				log.error("Couldnt send status msg, \""+dataToSend+"\" to: " + peer.toString());
			}
		}catch(Exception e)
		{
			if ( log.isErrorEnabled() ) {
				log.error("Exception", e);
				log.error("Couldnt send status msg, \""+dataToSend+"\" to: " + peer.toString());
			}
		}
	}
}
